/* PexifTool - $Revision$
 * Copyright (C) 2011 Petros Dolaschjan.  All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *	$Id$
 */
package de.pd.pjim2.controller.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ApplicationActionMap;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.swingx.JXBusyLabel;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTitledPanel;

import de.pd.pjim2.bean.PJFolderChangesBean;
import de.pd.pjim2.bean.PJImageFile;
import de.pd.pjim2.bean.PJImageSearchResult;
import de.pd.pjim2.bean.PJParameters;
import de.pd.pjim2.controller.PJImageController;
import de.pd.pjim2.controller.PJImageControllerException;
import de.pd.pjim2.controller.gui.dialog.AboutDialog;
import de.pd.pjim2.controller.gui.dialog.SettingsDialog;
import de.pd.pjim2.controller.gui.dialog.UserGuideDialog;
import de.pd.pjim2.event.ImageProcessEvent;
import de.pd.pjim2.log.WindowLogger;

/**
 * @author petros
 * 
 */
public class MainWindow extends FrameView implements ImageProcessEvent {

	private PJImageSearchResult mCurrentImages = new PJImageSearchResult();
	private Task<Object, Void> mCurrentTask;
	private CurrentState mCurrentState = CurrentState.NONE;

	private enum CurrentState {
		NONE, PREPARING, CANCELED_PREPARING, FINISHED_PREPARING, PROCESSING, FINISHED_PROCESSING, CANCELED_PROCESSING
	}

	public MainWindow(Application app) {
		super(app);
		initComponents();
		Application.getInstance().getContext().getResourceMap(getClass())
				.injectComponents(getFrame());

		WindowLogger logger = new WindowLogger(listModelLog);
		imageController = new PJImageController(logger, this);
	}

	/**
	 * Init the components.
	 * 
	 */
	private void initComponents() {
		ApplicationActionMap actionMap = Application.getInstance().getContext()
				.getActionMap(this);

		// -------------------
		// the frame
		getFrame().setPreferredSize(new Dimension(620, 600));
		getFrame().setResizable(false);
		getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getFrame().pack();
		getFrame().setLocationRelativeTo(null);
		Container contentPane = getFrame().getContentPane();
		contentPane.setLayout(new GridLayout(0, 1, 0, 0));
		
		int mainWidth = getFrame().getWidth();

		// -------------------
		// menu bar
		menuBar = new JMenuBar();
		setMenuBar(menuBar);

		// file menu
		JMenu fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');
		JMenuItem settingsItem = new JMenuItem(actionMap.get("settingsAction"));
		settingsItem.setMnemonic('s');
		fileMenu.add(settingsItem);
		JMenuItem exitItem = new JMenuItem(actionMap.get("exitAction"));
		exitItem.setMnemonic('x');
		fileMenu.add(exitItem);

		// help menu
		JMenu helpMenu = new JMenu("Help");
		fileMenu.setMnemonic('H');
		JMenuItem guideItem = new JMenuItem(actionMap.get("guideAction"));
		guideItem.setText("User Guide");
		helpMenu.add(guideItem);
		JMenuItem aboutItem = new JMenuItem(actionMap.get("aboutAction"));
		aboutItem.setText("About");
		aboutItem.setMnemonic('a');
		helpMenu.add(aboutItem);

		menuBar.add(fileMenu);
		menuBar.add(helpMenu);

		
		
		panelMain = new JXPanel();
		panelMain.setLayout(new MigLayout("wrap 1, fill, ins 0", "[grow]", "[110px][70px][grow]push[30px]"));
		panelMain.setPreferredSize(new Dimension(mainWidth, 500));
		contentPane.add(panelMain);

		// -------------------
		// the settings panel
		panelSettings = new JXTitledPanel("Settings");
		//panelSettings.setBounds(0, 0, mainWidth, 100);
		panelSettings.setBorder(BorderFactory.createEmptyBorder());
		panelMain.add(panelSettings, "grow");

		JPanel settingsParent = new JPanel();
		settingsParent.setLayout(null);
		mlabel = new JLabel("Directory:");
		mlabel.setBounds(6, 12, 77, 16);
		settingsParent.add(mlabel);

		tfDirectory = new JTextField();
		tfDirectory.setBounds(80, 6, 380, 28);
		settingsParent.add(tfDirectory);
		
		btnBrowse = new JButton(actionMap.get("browseAction"));
		btnBrowse.setBounds(477, 7, 117, 29);
		btnBrowse.setText("Browse");
		settingsParent.add(btnBrowse);

		// -------------------
		// the checkboxes
		panelCheckboxes = new JPanel();
		panelCheckboxes.setBounds(0, 40, 594, 33);
		settingsParent.add(panelCheckboxes);

		cbMove = new JCheckBox("Move");
		cbMove.setToolTipText("The images will be moved into directories based on their date");
		cbRename = new JCheckBox("Rename");
		cbRename.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent pE) {
				JCheckBox cb = (JCheckBox) pE.getSource();
				tfOffset.setEnabled(cb.isSelected());
			}
		});
		cbRename.setToolTipText("The images will be renamed using the date pattern");
		cbRotate = new JCheckBox("Rotate");
		cbRotate.setToolTipText("The images will be automatically rotated");
		JLabel lblOffset = new JLabel("Time Offset");
		lblOffset.setFont(cbRotate.getFont());
		lblOffset.setToolTipText("The time offset in hours. E.g.: If you want to subtract the time by 1 hour, enter -1.");
		tfOffset = new JTextField();
		tfOffset.setText("0");
		tfOffset.setPreferredSize(new Dimension(50,25));
		tfOffset.setEnabled(false);
		
		cbSubdir = new JCheckBox("Scan Subdirectories");
		//cbSubdir.setBounds(tfOffset.getX() + tfOffset.getWidth() + 5, 6, 110, 28);
		cbSubdir.setToolTipText("Scan also subdirectories");

		panelCheckboxes.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
		panelCheckboxes.add(cbMove);
		panelCheckboxes.add(cbRotate);
		panelCheckboxes.add(cbRename);
		panelCheckboxes.add(lblOffset);
		panelCheckboxes.add(tfOffset);
		panelCheckboxes.add(cbSubdir);

		panelSettings.setContentContainer(settingsParent);

		// -------------------
		// the buttons
		JXTitledPanel panelButtons = new JXTitledPanel("Actions");
		panelButtons.setBorder(BorderFactory.createEmptyBorder());
		//panelButtons.setBounds(0, getYPosAfterComponent(panelSettings, 5), mainWidth, 60);
		panelMain.add(panelButtons, "grow");

		JPanel panelButtonsContainer = new JPanel();
		panelButtonsContainer.setLayout(null);
		// the prepare, preview, cancel buttons
		btnCancel = new JButton(actionMap.get("cancelAction"));
		btnCancel.setBounds(477, 5, 117, 29);
		panelButtonsContainer.add(btnCancel);

		btnPrepare = new JButton(actionMap.get("getPrepareTask"));
		btnPrepare.setBounds(10, 5, 117, 29);
		panelButtonsContainer.add(btnPrepare);

		btnProcess = new JButton(actionMap.get("getProcessTask"));
		btnProcess.setBounds(135, 5, 117, 29);
		panelButtonsContainer.add(btnProcess);
		panelButtons.setContentContainer(panelButtonsContainer);

		// -------------------
		// the bottom panel
		panelBottom = new JXTitledPanel("Workspace");
		panelBottom.setBorder(BorderFactory.createEmptyBorder());
		int bottomHeight = getFrame().getHeight() - panelButtons.getHeight()
				- panelSettings.getHeight() - 90;
		//panelBottom.setBounds(0, getYPosAfterComponent(panelButtons, 5), mainWidth,
		//		bottomHeight);
		panelMain.add(panelBottom, "grow");

		// the scroll pane
		listModelLog = new DefaultListModel();
		// listLog.setCellRenderer(new LogListCellRenderer());

		panelScrollContent = new JPanel();
		scrollPainMain = new JScrollPane(panelScrollContent);

		panelScrollContent.setLayout(new GridLayout(0, 2));
		panelScrollContent.setBackground(new Color(238, 238, 238));
		panelBottom.setContentContainer(scrollPainMain);

		// -------------------
		// the progress panel
		panelProgress = new JPanel();
		panelProgress.setBounds(0, getYPosAfterComponent(panelButtons, 5), mainWidth,
				bottomHeight);
		panelProgress.setVisible(false);

		// -------------------
		// status panel
		JPanel panelStatus = new JPanel();
		panelStatus.setLayout(null);
		//panelStatus.setBounds(0, getYPosAfterComponent(panelBottom, 5), mainWidth, 28);

		lblLoading = new JLabel("Loading");
		lblLoading.setBounds(10, 3, 400, 20);
		panelStatus.add(lblLoading);

		// the busy icon
		busyLabel = new JXBusyLabel();
		busyLabel.setBounds(570, 0, 30, 30);
		busyLabel.setName("busyLabel");
		busyLabel.getBusyPainter().setHighlightColor(
				new Color(44, 61, 146).darker());
		busyLabel.getBusyPainter().setBaseColor(
				new Color(168, 204, 241).darker());
		busyLabel.setVisible(false);
		panelStatus.add(busyLabel);
		panelMain.add(panelStatus, "grow");

		updateFormBasedOnStatus();

		// -------------------
		// progress bar

		// TODO: Remove
		//tfDirectory.setText("/Users/petros/tmp/rotit");
	}

	/**
	 * Returns the Y position after a component + the gap. Convenient for
	 * placing a component right after another one.
	 * 
	 * @param pComp
	 * @param pVGap
	 * @return
	 */
	private int getYPosAfterComponent(Component pComp, int pVGap) {
		return pComp.getY() + pComp.getHeight() + pVGap;
	}

	// -------------------- Actions

	/**
	 * Opens the file browser.
	 * 
	 */
	@Action
	public void browseAction() {
		JFileChooser jfc = new JFileChooser();
		jfc.setMultiSelectionEnabled(false);
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		File curDir = new File(tfDirectory.getText());
		if (curDir.exists()) {
			jfc.setCurrentDirectory(curDir);
		}
		int selection = jfc.showOpenDialog(getFrame());
		if (selection == JFileChooser.APPROVE_OPTION) {
			tfDirectory.setText(jfc.getSelectedFile().getAbsolutePath());
		}
	}

	@Action
	public void exitAction() {
		System.exit(0);
	}

	@Action
	public void cancelAction() {
		if (mCurrentTask.getUserCanCancel()) {
			System.out.println("Canceling");
			mCurrentTask.cancel(true);
		}

	}
	
	@Action
	public void settingsAction() {
		SettingsDialog sd = new SettingsDialog(getFrame());
		sd.setVisible(true);
		
	}
	
	@Action
	public void aboutAction() {
		AboutDialog sd = new AboutDialog(getFrame());
		sd.setVisible(true);
		
	}
	
	@Action
	public void guideAction() {
		UserGuideDialog ugd = new UserGuideDialog(getFrame());
		ugd.setVisible(true);
	}
	// -------------------- Controlling methods

	/**
	 * Returns the parameters based on the users selection.
	 * 
	 * @return
	 */
	private PJParameters getParams() {
		PJParameters params = new PJParameters();
		params.setSrcDir(tfDirectory.getText());
		params.setMoveImages(cbMove.isSelected());
		params.setRenameImages(cbRename.isSelected());
		params.setScanSubfolders(cbSubdir.isSelected());
		params.setRotateImages(cbRotate.isSelected());
		if(cbRename.isSelected()) {
			params.setDateTimeOffset(Integer.parseInt(tfOffset.getText()));
		}
		return params;
	}

	/**
	 * Validate the form.
	 * 
	 * @return
	 */
	private boolean validate() {
		// validation
		try {
			if(cbRename.isSelected())
				Integer.parseInt(tfOffset.getText());
		} catch(Exception ex) {
			showErrorMessage("Error", "Please enter only a numeric value for Offset");
			return false;
		}
		if (tfDirectory.getText().length() == 0) {
			showErrorMessage("Error", "Please select a directory");
			return false;
		}

		if (!(cbMove.isSelected() || cbRotate.isSelected() || cbRename
				.isSelected())) {
			showErrorMessage("Error", "Please select at least one option");
			return false;
		}
		return true;
	}

	/**
	 * Indicates that the loading has started.
	 * 
	 */
	private void loadingStarted() {
		busyLabel.setBusy(true);
		busyLabel.setVisible(true);
		btnProcess.setEnabled(false);
	}

	/**
	 * Loading stopped.
	 * 
	 */
	private void loadingStopped() {
		busyLabel.setBusy(false);
		busyLabel.setVisible(false);
		btnProcess.setEnabled(true);
	}
	
	private void clearScrollContent() {
		//SwingUtilities.invokeLater(new Runnable() {
			
			//@Override
			//public void run() {
				panelScrollContent.removeAll();
				panelScrollContent.updateUI();
		//	}
		//});
		
	}
	
	private void showErrorMessage(String pTitle, String pText) {
		JOptionPane.showMessageDialog(getFrame(),
				pText, pTitle,
				JOptionPane.ERROR_MESSAGE);
	}

	private void updateFormBasedOnStatus() {
		// TEST ZONE

		switch (mCurrentState) {
		case PREPARING:
			loadingStarted();
			btnCancel.setEnabled(true);
			btnPrepare.setEnabled(false);
			btnProcess.setEnabled(false);
			lblLoading.setText("Preparing images for processing: ");
			break;
		case PROCESSING:
			loadingStarted();
			btnCancel.setEnabled(true);
			btnPrepare.setEnabled(false);
			btnProcess.setEnabled(false);
			lblLoading.setText("Processing pictures...");
			break;
		case CANCELED_PREPARING:
			loadingStopped();
			btnCancel.setEnabled(false);
			btnPrepare.setEnabled(true);
			btnProcess.setEnabled(false);
			lblLoading.setText("");
			clearScrollContent();
			break;
		case CANCELED_PROCESSING:
			loadingStopped();
			btnCancel.setEnabled(false);
			btnPrepare.setEnabled(true);
			btnProcess.setEnabled(false);
			lblLoading.setText("");
			clearScrollContent();
			break;
		case FINISHED_PREPARING:
			loadingStopped();
			btnCancel.setEnabled(false);
			btnPrepare.setEnabled(true);
			btnProcess.setEnabled(true);
			lblLoading.setText("");
			if (mCurrentImages.getTotalChanges() == 0) {
				JOptionPane
						.showMessageDialog(
								getFrame(),
								"<html><b>No changes found</b><br>Please update your settings and try it again.</html>",
								"No changes found",
								JOptionPane.INFORMATION_MESSAGE);
				btnProcess.setEnabled(false);
			} else {
				displayFolderChanges();
			}
			break;
		case FINISHED_PROCESSING:
			loadingStopped();
			btnCancel.setEnabled(false);
			btnPrepare.setEnabled(true);
			btnProcess.setEnabled(false);
			lblLoading.setText("");
			break;
		default:
			loadingStopped();
			btnCancel.setEnabled(false);
			btnPrepare.setEnabled(true);
			btnProcess.setEnabled(false);
			lblLoading.setText("");
			break;
		}

	}

	/**
	 * Displays the folder icon panels in the scroll pane.
	 * 
	 */
	private void displayFolderChanges() {
		List<PJFolderChangesBean> folders = mCurrentImages.getFolders();
		for (PJFolderChangesBean folder : folders) {
			if (folder.getTotalChanges() == 0)
				continue;
			ChangesPanel cp = new ChangesPanel(folder);
			panelScrollContent.add(cp);
		}
	}

	private boolean confirmProcess() {
		String msg = "Do you really want to proceed with the changes?";
		int confirmDialog = JOptionPane.showConfirmDialog(getFrame(), msg,
				"Proceed?", JOptionPane.YES_NO_OPTION);
		return confirmDialog == JOptionPane.OK_OPTION;
	}

	// -------------------- Tasks
	@Action
	public Task<Object, Void> getPrepareTask() {
		return new prepareTask(getApplication());
	}

	/**
	 * Prepares the images for further processing.
	 * 
	 * @author petros
	 * 
	 */
	private class prepareTask extends Task<Object, Void> {

		/**
		 * @param pApplication
		 */
		public prepareTask(Application pApplication) {
			super(pApplication);
			setUserCanCancel(true);
			mCurrentTask = this;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.swing.SwingWorker#doInBackground()
		 */
		@Override
		protected Boolean doInBackground() throws Exception {
			if (!validate()) {
				mCurrentState = CurrentState.NONE;
				return Boolean.FALSE;
			}
			mCurrentState = CurrentState.PREPARING;
			updateFormBasedOnStatus();
			clearScrollContent();

			PJParameters params = getParams();
			mCurrentImages = imageController.prepare(params);
			return Boolean.TRUE;
		}

		@Override
		protected void failed(Throwable pCause) {
			super.failed(pCause);
			PJImageControllerException ex = (PJImageControllerException) pCause;
			switch (ex.getExType()) {
			case DIR_NOT_FOUND:
				showErrorMessage("Error", "The selected directory does not exist");
				break;

			default:
				break;
			}
			mCurrentState = CurrentState.CANCELED_PREPARING;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.jdesktop.application.Task#cancelled()
		 */
		@Override
		protected void cancelled() {
			super.cancelled();
			imageController.cancel();
			mCurrentState = CurrentState.CANCELED_PREPARING;
		}

		@Override
		protected void succeeded(Object pResult) {
			super.succeeded(pResult);
			boolean result = ((Boolean) pResult).booleanValue();
			mCurrentState = result ? CurrentState.FINISHED_PREPARING
					: CurrentState.NONE;
			System.out.println("Got " + mCurrentImages.getTotalChanges() + "changes on " 
					+ mCurrentImages.getTotalImagesToChange() +
					"images");
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.jdesktop.application.Task#finished()
		 */
		@Override
		protected void finished() {
			super.finished();
			updateFormBasedOnStatus();
			System.out.println("Finished");
		}

	}

	/**
	 * Returns a new instance of the process task.
	 * 
	 * @return
	 */
	@Action
	public Task<Object, Void> getProcessTask() {
		if (!confirmProcess())
			return null;
		clearScrollContent();
		return new processTask(getApplication());
	}

	/**
	 * Process the prepared images.
	 * 
	 * @author petros
	 * 
	 */
	private class processTask extends Task<Object, Void> {

		/**
		 * @param pApplication
		 */
		public processTask(Application pApplication) {
			super(pApplication);
			setUserCanCancel(true);
			mCurrentTask = this;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.swing.SwingWorker#doInBackground()
		 */
		@Override
		protected Object doInBackground() throws Exception {
			if (!mCurrentState.equals(CurrentState.FINISHED_PREPARING)) {
				throw new IllegalStateException(
						"Trying to process while the current state is not prepare finished!");
			}
			mCurrentState = CurrentState.PROCESSING;
			updateFormBasedOnStatus();
			

			imageController.proccess(mCurrentImages);
			
			return null;
		}

		@Override
		protected void cancelled() {
			super.cancelled();
			imageController.cancel();
			mCurrentState = CurrentState.CANCELED_PROCESSING;
		}
		
		

		@Override
		protected void succeeded(Object pResult) {
			super.succeeded(pResult);
			mCurrentState = CurrentState.FINISHED_PROCESSING;
		}

		@Override
		protected void finished() {
			super.finished();
			updateFormBasedOnStatus();
		}

	}

	/**
	 * 
	 */
	private JXPanel panelMain;
	private JXTitledPanel panelSettings;
	private JLabel mlabel;
	private JTextField tfDirectory;
	private JButton btnBrowse;
	private JCheckBox cbMove;
	private JCheckBox cbRename;
	private JCheckBox cbSubdir;
	private JPanel panelCheckboxes;
	private JCheckBox cbRotate;
	private JXTitledPanel panelBottom;
	private JScrollPane scrollPainMain;
	private JLabel lblLoading;
	private DefaultListModel listModelLog;
	private JXBusyLabel busyLabel;
	private JButton btnProcess;
	private JButton btnCancel;
	private JButton btnPrepare;
	private PJImageController imageController;
	private JMenuBar menuBar;
	private JPanel panelProgress;
	private JPanel panelScrollContent;
	private Map<String, ProcessedFolderPanel> processFolderMap = new HashMap<String, ProcessedFolderPanel>();
	private JTextField tfOffset;

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.pd.pjim2.event.ImageProcessEvent#didFinishScanning()
	 */
	@Override
	public void didFinishScanning() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.pd.pjim2.event.ImageProcessEvent#didFinishProcessing()
	 */
	@Override
	public void didFinishProcessing() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.pd.pjim2.event.ImageProcessEvent#didScanFolder(java.lang.String)
	 */
	@Override
	public void didScanFolder(PJFolderChangesBean pChangesBean) {
		if (pChangesBean.getTotalChanges() == 0)
			return;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.pd.pjim2.event.ImageProcessEvent#didScanImage(de.pd.pjim2.bean.PJImageFile
	 * )
	 */
	@Override
	public void didScanImage(PJImageFile pImageFile) {
		// TODO Auto-generated method stub
		lblLoading.setText("Preparing images for processing: "
				+ pImageFile.getSrcFile().getName());
	}

	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.pd.pjim2.event.ImageProcessEvent#didStartProcessingFolder(java.io.
	 * File)
	 */
	@Override
	public void didStartProcessingFolder(PJFolderChangesBean pFolder) {
		if(pFolder.getTotalChanges() == 0) return;
		System.out.println("adding " + pFolder.getDir());
		ProcessedFolderPanel folderPanel = processFolderMap.get(pFolder.getDir());
		if(folderPanel == null) {
			folderPanel = new ProcessedFolderPanel(new File(pFolder.getDir()));
			processFolderMap.put(pFolder.getDir(), folderPanel);
			
		}
		folderPanel.startedProcessing(pFolder.getTotalImagesToChange());
		System.out.println("Max: " + folderPanel.getProgBar().getMaximum());
		
		panelScrollContent.add(folderPanel);
		panelScrollContent.updateUI();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.pd.pjim2.event.ImageProcessEvent#didProcessImage(de.pd.pjim2.bean.
	 * PJImageFile)
	 */
	@Override
	public void didProcessImage(String pImage) {
		ProcessedFolderPanel folderPanel = processFolderMap.get(pImage);
		if(folderPanel == null) return;
		//System.out.println("reading " + pImage);
		JProgressBar progBar = folderPanel.getProgBar();
		progBar.setValue(progBar.getValue() + 1);
		System.out.println("Prog max: " + progBar.getMaximum() + " cur val " + progBar.getValue());
		if(progBar.getMaximum() == progBar.getValue()) {
			
			folderPanel.finishedProcessing();
		}
	}
}
